<template>
  <Dialog :visible.sync="innerVisible" :title="isEdit ? '编辑商品' : '新增商品'">
    <el-row class="row">
      <el-col :span="24" class="col-md-12">
        <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="110px">
          <Portlet title="产品信息">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="厂家名称" prop="manufacturersName" :rules="[
                    {required: true, message: '厂家名称必须', trigger: 'blur'}
                  ]">
                  <el-input disabled v-model="model.manufacturersName"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="商品型号" prop="productOutNo" :rules="[
                    {required: true, message: '商品型号必须', trigger: 'blur'}
                  ]">
                  <el-input :disabled="disabledFormItem('productOutNo')" v-model="model.productOutNo"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="商品名称" prop="productName" :rules="[
                    {required: true, message: '商品名称必须', trigger: 'blur'}
                  ]">
                  <el-input :disabled="disabledFormItem('productName')" v-model="model.productName"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="商品类别" prop="productCodeArr">
                  <product-select :disabled="disabledFormItem('bigClassNo') && disabledFormItem('middleClassNo')"
                                  ref="productSelect" v-model="model.productCodeArr"></product-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="材料类型" prop="storageTypeCode" :rules="[
                  ]">
                  <el-select :disabled="disabledFormItem('storageTypeCode')" v-model="model.storageTypeCode">
                    <el-option v-for="item in storageTypeArr" :key="item.value" :label="item.text"
                               :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="规格" prop="standard" :rules="[
                  ]">
                  <el-input :disabled="disabledFormItem('standard')" v-model="model.standard"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>

          <Portlet title="包件信息">
            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label-width="0" prop="packageInfos" :rules="[
                  {required: true, message: '包件信息必须', trigger: 'change', type: 'array'}
                ]">
                  <PackageTable :isUpdate="isEdit" :original="originalPackageInfos"
                                v-model="model.packageInfos"></PackageTable>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>
        </el-form>
      </el-col>
    </el-row>

    <div slot="footer">
      <el-button @click="innerVisible = false">取消</el-button>
      <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">
        {{ id ? '保存' : '新增'}}
      </el-button>
    </div>
  </Dialog>
</template>
<script>
import {copy, dotData, alert, confirm} from '@/utils'
import {filterDataBaseDictionary} from '@/filters'
import {isFormatNumber, isPhone} from '@/utils/validate'
import {getSubDictListOfParentCode} from '@/utils/selectOptions'
import PackageTable from '@/views/oms/basicData/manufactorPro/PackageTable'
import L from 'lodash'

export default {
  name: 'basicDataManufactorProCreate',
  components: {
    PackageTable
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    item: { // 基本的厂家信息
      type: Object,
      default() {
        return {}
      }
    },
    id: {
      type: String,
      default: ''
    }
  },
  filters: {
    filterDataBaseDictionary
  },
  watch: {
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        this.resetFields()
        this.originalPackageInfos = []
        this.model.packageInfos = []
        this.detail = {}
        this.$nextTick(_ => {
          this.setData()
          this.httpGetData()
        })
      }
      this.innerVisible = val
    },
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    }
  },
  data() {
    return {
      routeName: this.$route.name,
      loading: false,
      cargoOwnerLoading: false,
      productionSelectModalVisible: false, // 产品选择弹窗默认关闭
      model: {
        productOutNo: '',
        productName: '',
        manufacturersId: '',
        standard: '',
        style: '',
        customProperty: '',
        productUnit: '',
        color: '',
        storageTypeCode: '',
        packageInfos: [],
        productCodeArr: [],
        totalPackageNum: '',
        totalVolume: '',
        totalWeight: '',
        bigClassNo: '',
        middleClassNo: '',
        manufacturersName: ''
      },
      innerVisible: false,
      storageTypeArr: [],
      cargoOwnerArr: [],
      originalPackageInfos: [],
      detail: {}
    }
  },
  computed: {
    isEdit() { // 是不是编辑
      return !!this.id
    }
  },
  created() {
    // 存储类型
    getSubDictListOfParentCode('STORAGETYPE').then(arr => {
      this.storageTypeArr = arr
    })
  },
  methods: {
    isFormatNumber,
    isPhone,
    httpPost(url) {
      let data = copy(this.model, true)
      if (this.id) {
        data.id = this.id
      }
      data.bigClassNo = data.productCodeArr[0]
      data.middleClassNo = data.productCodeArr[1]
      delete data.productCodeArr
      return this.$ajax.post(url, data)
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.loading = true
        let title = this.id ? '编辑成功' : '新增成功'
        let url = '/ms-warehouse-order/basicData/modifyManufacturersProductInfo'
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$emit('refresh', true)
            confirm(title, title, {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).finally(_ => {
              this.innerVisible = false
              this.resetFields()
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      try {
        const elForm = this.$refs.elForm
        if (elForm) {
          this.$refs.elForm.resetFields()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 后端搜索
    remoteQuery(query) {
      this.cargoOwnerLoading = true
      this.remoteMethod(query, this)
    },
    // 后端搜索 函数防抖
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      _this.$ajax.get('/ms-warehouse-order/basicData/findManufacturersList', {name: query}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.manufacturersName,
                value: v.id
              })
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000),
    setData() {
      if (!this.isEdit) {
        this.$nextTick(_ => {
          this.model.manufacturersId = dotData(this.item, 'id')
          this.model.manufacturersName = dotData(this.item, 'manufacturersName')
        })
      }
    },
    // 禁用一个表单元素
    disabledFormItem(key) {
      return !!dotData(this.detail, key)
    },
    httpGetData() {
      if (this.id) {
        this.$ajax.get('/ms-warehouse-order/basicData/findManufacturersProductInfo', {id: this.id}).then(response => {
          if (!response.data) {
            return
          }
          this.detail = response.data
          this.model.productOutNo = dotData(response, 'data.productOutNo')
          this.model.productName = dotData(response, 'data.productName')
          this.model.manufacturersId = dotData(response, 'data.manufacturersId')
          this.model.manufacturersName = dotData(response, 'data.manufacturersName')
          this.model.standard = dotData(response, 'data.standard')
          this.model.style = dotData(response, 'data.style')
          this.model.productUnit = dotData(response, 'data.productUnit')
          this.model.customProperty = dotData(response, 'data.customProperty')
          this.model.color = dotData(response, 'data.color')
          this.model.storageTypeCode = dotData(response, 'data.storageTypeCode')
          const packageInfos = dotData(response, 'data.packageInfos')
          if (Array.isArray(packageInfos)) {
            this.model.packageInfos = packageInfos.map(v => {
              v.packageName = v.name
              return v
            })
            this.originalPackageInfos = copy(this.model.packageInfos, true)
          }
          this.model.totalPackageNum = dotData(response, 'data.totalPackage')
          this.model.totalVolume = dotData(response, 'data.totalVolume')
          this.model.totalWeight = dotData(response, 'data.totalWeight')
          let bigClassNo = dotData(response, 'data.bigClassNo')
          let middleClassNo = dotData(response, 'data.middleClassNo')
          if (bigClassNo && middleClassNo) {
            this.model.productCodeArr = [bigClassNo, middleClassNo]
            this.model.productCodeArr.push(middleClassNo)
          }
        })
      }
    }
  }
}
</script>
